<template>
    <!-- 模板代码保持不变 -->
    <v-content ref="content" padding-top="100" single>
        <div class="close"></div>
        <div class="title padding">手机号注册/登录</div>
        <div class="tip padding">未注册的手机号将自动创建账户</div>
        <div class="tab">
            <div
                class="tab-item"
                :class="[
                    {
                        active: type === 'face',
                    },
                ]"
                @click="type = 'face'"
            >
                人脸登录
            </div>
            <div
                class="tab-item"
                :class="[
                    {
                        active: type === 'password',
                    },
                ]"
                @click="type = 'password'"
            >
                密码登录
            </div>
        </div>
        <div class="form-item auto-height" v-show="type === 'face'">
			<span ><a href="http://localhost:5000/faceLogin">如果没有跳转, 点击手动跳转</a></span> 
        </div>

        <div class="form-item auto-height" v-show="type==='password'">
            <div class="value">
                <div class="area-code">+86</div>
                <input v-model="formData.phone" type="number" class="input" placeholder="请输入账号" maxlength="11" />
            </div>
        </div>
        <div class="form-item auto-height" v-show="type === 'sms'">
            <div class="value">
                <input v-model="formData.smsCode" type="text" class="input" placeholder="请输入短信验证码" />
                <div
                    class="send-code"
                    :class="[
                        {
                            disabled: veCodeTime < 60,
                        },
                    ]"
                    @click="sendCode(formData.phone)"
                >
                    {{ veCodeText }}
                </div>
            </div>
        </div>
        <div class="form-item auto-height" v-show="type === 'password'">
            <div class="value">
                <input v-model="formData.password" type="password" class="input" placeholder="请输入密码" />
            </div>
        </div>
        <div class="button primary bg radius" @click="onLogin" v-show='type==="password"'>确认登录</div>
        <div class="agree">
            <div class="checkbox primary" :class="[{ active: argee }]" @click="argee = !argee"></div>
            登录即代表您已同意
            <span class="primary" @click="toPage('/pages/mine/agreement', { type: '0' })">《{{ message.title }}》</span>
        </div>
        <div class="agree" style="justify-content: center">
            还没有账号？
            <span class="primary" @click="toPage('/pages/login/register')">立即注册</span>
        </div>
    </v-content>
</template>

<script>
import mixins from "@/mixins"
import smsMixin from "@/mixins/vecode"
import MD5 from "js-md5"

export default {
    name: "login",
    mixins: [
        mixins,
        smsMixin({
            url: "/api/sendCode",
            type: "1",
        }),
    ],
    data() {
        return {
            formData: {
                phone: "",
                smsCode: "",
                password: "",
                nickName: '',
            },
            argee: true,
            message: "",
            imageUrl: '',
            type: "password", // sms password
            pwdVisible: false,
            selectedFile: null,
            stream: null,
            photoUrl: null
        }
    },
    watch: {
        // 监听 type 数据的变化
        type(newVal) {
            if (newVal === 'face') {
                // 当新值等于 'face' 时，执行对应方法
                this.handleFaceType();
            }
        }
    },
    computed: {
        submitUrl() {
            if (this.type === "sms") {
                return "/memberLogin/codeLogin"
            }
            return "/memberLogin/accountLogin"
        },
        submitData() {
            if (this.type === "sms") {
                return {
                    phone: this.formData.phone,
                    smsCode: this.formData.smsCode,
                }
            } else if (this.type === "password") {
                return {
                    phone: this.formData.phone,
                    password: MD5(this.formData.password),
                }
            } else {
                return {
                    nickName: this.formData.nickName,
                    password: MD5("11223344"),
                }
            }
        },
    },
    mounted() {
    	this.init();
    },
	created() {
	    // 获取 URL 中的查询参数
	    const query = new URLSearchParams(window.location.search);
	    var isSuccess = query.get('loginType');
	    console.log('登录类型:', isSuccess);
	    // 可以根据 loginType 做相应的处理
	    if (isSuccess === 'face_login') {
	      var username = sessionStorage.getItem("username_important")
		  var password = MD5("11223344");
		  this.formData.nickName=username;
		  console.log(this.formData);
		  this.type='face';
		  this.onLogin();
	    }
	  },
	methods: {
        init() {
            this.getMessage();
			this.startMes();
            // this.getFaceRes()
        },
		upFaceImg(){
			
		},
        // 定义对应的处理方法
        handleFaceType() {
            console.log('当前 type 的值为 face，执行了对应方法');
        },
        chooseImage() {
            uni.chooseImage({
                count: 1, // 最多可以选择的图片张数
                sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                success: (res) => {
                    this.imagePath = res.tempFilePaths[0];
                    console.log('选择的图片路径:', this.imagePath);
                    // 选择图片成功后调用上传方法
                    this.uploadFile(this.imagePath);
                },
                fail: (err) => {
                    console.error('选择图片失败:', err);
                }
            });
        },
        uploadFile(filePath) {
            uni.uploadFile({
                url: 'http://127.0.0.1:5000/face_identify', // 上传的接口地址
                filePath: filePath, // 要上传文件的本地临时路径
                name: 'image', // 上传文件的字段名
                success: (res) => {
                    if (res.statusCode === 200) {
                        uni.showToast({
                            title: '文件上传成功',
                            icon: 'success'
                        });
                        this.formData.nickName = JSON.parse(res.data).name
                        this.formData.password = MD5("11223344")
                        this.onLogin()
                        // 可以根据响应内容做进一步处理
                    } else {
                        uni.showToast({
                            title: '文件上传失败',
                            icon: 'none'
                        });
                        console.error('上传错误:', res.errMsg);
                    }
                },
                fail: (err) => {
                    uni.showToast({
                        title: '文件上传失败',
                        icon: 'none'
                    });
                    console.error('上传错误:', err);
                }
            });
        },
        async onLogin() {
            try {
                if (this.type === "password") {
                    if (!this.formData.phone) {
                        throw "请输入手机号"
                    }
                    if (this.formData.phone.length !== 11 || this.formData.phone[0] != "1") {
                        throw "请输入正确的手机号"
                    }
                }
                if (this.type === "sms") {
                    if (!this.formData.smsCode) {
                        throw "请输入验证码"
                    }
                } else {
                    if (!this.formData.password) {
                        throw "请输入密码"
                    }
                }

                if (!this.argee) {
                    uni.showModal({
                        title: "提示",
                        content: "是否同意用户协议?",
                        success: res => {
                            if (res.confirm) {
                                this.argee = true

                                this.onLogin()
                            }
                        },
                    })

                    return
                }
                console.log(this.submitData)
                const data = await this.$http({
                    url: this.submitUrl,
                    method: "POST",
                    data: this.submitData,
                })

                uni.setStorageSync("token", data.token)
                uni.setStorageSync("refresh_token", data.refreshToken)
                const userInfo = await this.$axios.get("/api/member/member/info", {
                    id: data.id,
                })
                this.$store.commit("setUserInfo", userInfo)
                uni.showToast({
                    title: "登录成功",
                    icon: "success",
                })
                setTimeout(() => {
                    this.toPage("/pages/index/index", "reLaunch")
                }, 1200)
            } catch (error) {
                this.showMessage.error(error)
            }
        },
        async getMessage() {
            this.message = await this.$axios.get("/api/system/protocol/getByCode?code=USER")
        },
        async getFaceRes() {
            this.message = await this.$axios.get("http://127.0.0.1:5000/face_update")
        },
		async startMes() { 
		    sessionStorage.setItem("username","123456")
			
		},
        
    },
}
</script>

<style lang="scss" scoped>
    /* 样式代码保持不变 */
    .close {
        --width: 50rpx;

        position: relative;
        margin-left: 30rpx;
        width: var(--width);
        height: var(--width);
        &::before {
            content: "";
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto;
            width: 2rpx;
            height: 100%;
            background-color: #000;
            transform: rotate(45deg);
        }
        &::after {
            content: "";
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto;
            width: 2rpx;
            height: 100%;
            background-color: #000;
            transform: rotate(-45deg);
        }
    }

    .title {
        font-weight: 700;
        font-size: 40rpx;
        padding-top: 105rpx;
        padding-bottom: 10rpx;
        color: #333;
    }
    .tip {
        font-size: 26rpx;
        color: #666;
        letter-spacing: 2rpx;
    }
    .tab {
        padding-top: 80rpx;
        padding-bottom: 20rpx;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        margin-bottom: 25rpx;
        .tab-item {
            padding-inline: 30rpx;
            font-size: 30rpx;
            font-weight: 700;
            position: relative;
            padding-bottom: 20rpx;
            &::before {
                content: "";
                position: absolute;
                bottom: 0;
                left: 0;
                right: 0;
                margin: auto;
                height: 10rpx;
                border-radius: 100px;
                background: $primary;
                width: 1em;
                opacity: 0;
            }
            &.active {
                &::before {
                    opacity: 1;
                }
            }
        }
    }

    .form-item {
        padding-block: 20rpx;
        .value {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            .input {
                background: #fff;
                flex: 1;
                font-size: 26rpx;
                height: 60rpx;
            }

            .area-code {
                border-right: 1px solid #000;
                color: #333;
                height: 1.2em;
                padding-right: 20rpx;
                font-size: 30rpx;
            }
            .send-code {
                font-size: 26rpx;
                color: $primary;
                &.disabled {
                    color: #ccc;
                }
            }
        }
    }

    .button {
        margin: auto;
        margin-top: 120rpx;
        width: 660rpx;
        height: 90rpx;
    }

    .agree {
        width: 660rpx;
        font-size: 24rpx;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        margin: auto;
        line-height: 4;
        color: #666;
    }
    /* 简单的样式设置 */
    .form-item {
        margin-bottom: 10px;
    }
    video {
        display: block;
        margin-bottom: 10px;
    }
</style>